<?php

namespace App\Console\Commands;

use App\Models\Ncdh\NcdhBettingtype;
use App\Models\Ncdh\NcdhIssue;
use App\Models\Ncdh\NcdhOrderDetailLog;
use App\Models\Ncdh\NcdhPayLog;
use App\User;
use App\UserCoinLog;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class NcdhFinishIssue extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ncdh:finishIssue';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'ncdh game open lottory';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        try {

            //查询正在进行的期号
            $currentIssue = NcdhIssue::getRunningIssue();

            $statusRunning = NcdhIssue::STATUS_RUNNING;
            $statusOpening = NcdhIssue::STATUS_OPENING;
            $statusFinished = NcdhIssue::STATUS_FINISHED;

            //  if (empty($currentIssue['id']) || $currentIssue['openAfter'] > -2) {  //没有进行中 或 还没到时间
            if (false) {
                return false;

            } else {    //可以开奖

                try {

                    echo "Issue: {$currentIssue['id']} begin\n";
                    echo "openAfter: {$currentIssue['openAfter']}\n";
                    echo "Time: " . date('Y-m-d H:i:s') . "\n";

                    DB::beginTransaction();
                    //设置为待开奖
                    $res = NcdhIssue::where('id', $currentIssue['id'])->where('status', $statusRunning)->update(['status' => $statusOpening]);
                    if (empty($res)) {
                        throw new \Exception("无法更新为待开奖状态");
                    }

                    //获取订单下详情
                    $orderDetail = NcdhOrderDetailLog::getOrderDetail($currentIssue['id']);

                    //获取开奖结果
                    $typeId = $this->get_rand(config('ncdh.win_type'));

                    //获取该类的上两级
                    $typeArr = config('ncdh.pay_type');
                    $secondtypeId = $typeArr[$typeId]['parentId'];
                    $thirdtypeId = $typeArr[$secondtypeId]['parentId'];

                    //最终开奖结果  第三级ID+第二级ID+第三级ID
                    $winType = $typeId . "," . $secondtypeId . "," . $thirdtypeId;

                    echo "winType: {$winType} \n";

                    //设置开奖结果
                    $issueItem = NcdhIssue::where('id', $currentIssue['id'])->where('status', $statusOpening)->first();

                    if (!empty($issueItem->id)) {   //待开奖

                        $res = NcdhIssue::where('id', $currentIssue['id'])->where('status', $statusOpening)->update(['status' => $statusFinished, 'win_type' => $winType,]);

                        if (empty($res)) {
                            throw new \Exception("无法更新为已开奖状态");
                        } else {

                            //记录订单详情的中奖标记
                            $winTypeArray = explode(",", $winType);

                            $rows = NcdhOrderDetailLog::updateWinType($currentIssue['id'], $winTypeArray);

                            echo "win rows: {$rows} \n";

                            $now = time();
                            //开奖成功，发放奖励

                            $orderDetailSumByTypeUserId = NcdhOrderDetailLog::getOrderDetailSumByTypeUserId($orderDetail);

                            foreach ($winTypeArray as $winTypeId) {

                                if (isset($orderDetailSumByTypeUserId[$winTypeId])) {

                                    echo "中奖详情：\n";
                                    echo print_r($orderDetailSumByTypeUserId[$winTypeId], true) . "\n";

                                    foreach ($orderDetailSumByTypeUserId[$winTypeId] as $userId => $gold) {

                                        //奖励金额
                                        $awardGold = $gold * $typeArr[$winTypeId]['odds'];

                                        //获取新的用户信息
                                        $user = User::find($userId);

                                        $userXYB = $user->XYB;
                                        //记录奖励
                                        $payLogModel = new NcdhPayLog();
                                        $payLogModel->user_id = $userId;
                                        $payLogModel->from_XYB = $userXYB;
                                        $payLogModel->add_XYB = $awardGold;
                                        $payLogModel->to_XYB = $userXYB + $gold;
                                        $payLogModel->issue = $currentIssue['id'];
                                        $payLogModel->order_id = 0;
                                        $payLogModel->add_time = $now;
                                        $payLogModel->update_time = $now;
                                        $payLogModel->save();

                                        //config/type.php    9 => '农场大亨下单'
                                        $key = '9-' . $userId . '-' . $awardGold . '-' . $currentIssue['id'];

                                        //business表  9 => 农场大亨战
                                        UserCoinLog::log(9, $userId, UserCoinLog::TYPE_XYB, $awardGold, '农场大亨开奖奖励', $key);
                                        
                                    }
                                } else {
                                    echo "没有中奖记录\n";
                                }
                            }
                        }
                    }

                    //创建下一期
                    $nextIssueId = NcdhIssue::createNextIssue();

                    if (empty($nextIssueId)) {
                        throw new \Exception("开奖后无法创建下一期", 3);
                    }
                    DB::commit();
                    echo "开奖成功\n";
                } catch (\Exception $e) {
                    DB::rollBack();
                    Log::debug($e);
                    echo "开奖失败: ", $e->getMessage(), "\n";
                }
            }
        } catch (\Exception $e) {
            Log::debug($e);
            echo "开奖失败: ", $e->getMessage(), "\n";
        }
        echo "Issue: {$currentIssue['id']} end\n\n";
    }

    /**
     * @function 计算概率
     * @param $proArr
     * @return int|string
     */
    public function get_rand($proArr)
    {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($proArr);
        //概率数组循环
        foreach ($proArr as $key => $proCur) {

            $randNum = mt_rand(1, $proSum);             //抽取随机数

            if ($randNum <= $proCur) {
                $result = $key;                         //得出结果
                break;
            } else {
                $proSum -= $proCur;
            }

        }
        unset ($proArr);
        return $result;
    }

}
